<?php


namespace App\Http\Service;


use App\Model\Articles;
use App\Model\Comment;
use App\Model\Vote;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VoteService
{
    /**
     * 赞
     * @param $type
     * @param $target_id
     * @throws \Exception
     */
    public static function voteUp($type, $target_id)
    {
        $v = Vote::where('type', $type)->where('user_id',Auth::id())->where('vote', 1)->where('target_id',$target_id)->first();
        if ($v){
            throw new \Exception('你已经点赞过了');
        }
        switch ($type){
            case 1 :
                $m = Articles::find($target_id);
                break;
            case 2:
                $m = Comment::find($target_id);
                break;
            default:
                throw new \Exception('请稍后重试');
        }
        try {
            DB::transaction(function () use ($type, $m){
                //点赞记录
                Vote::create(['user_id'=>Auth::id(), 'vote'=>1, 'target_id'=>$m->id, 'type'=>$type]);

                $m->increment('thumb');
            });
        } catch (\Throwable $e) {
            Log::error($e);
            throw new \Exception('请稍后重试');
        }
    }

    /**
     * 取消赞
     * @param $type
     * @param $target_id
     * @throws \Exception
     */
    public static function unVoteUp($type, $target_id)
    {
        $v = Vote::where('type', $type)->where('user_id',Auth::id())->where('vote', 1)->where('target_id',$target_id)->first();
        if (!$v){
            throw new \Exception('你还没有点赞');
        }
        switch ($type){
            case 1 :
                $m = Articles::find($target_id);
                break;
            case 2:
                $m = Comment::find($target_id);
                break;
            default:
                throw new \Exception('请稍后重试');
        }
        try {
            DB::transaction(function () use ($type, $m, $v){
                //点赞记录
                $v->delete();

                $m->decrement('thumb');
            });
        } catch (\Throwable $e) {
            Log::error($e);
            throw new \Exception('请稍后重试');
        }
    }

    /**
     * 踩 待实现
     * @param $type
     * @param $target_id
     */
    public static function voteDown($type, $target_id)
    {
    }
}